import React, { useState, useRef, useEffect } from 'react';
import { Form, Tabs, Row, Col, Button, message } from 'antd';
import DefineInterface from './DefineInterface';
import DefineReturn from './DefineReturn';
import services from '../../../../../services/api';
import '../index.less';

const initValue = {
  thirdList: [],
};

const InterfaceManageAdd = (props) => {
  const { form } = props;
  const [activeKey, setActiveKey] = useState('0');
  const [value, setValue] = useState(initValue);
  const defineInterfaceRef = useRef();
  const defineReturnRef = useRef();
  // 通过path区分主备接口 分流接口 true 为主备 false分流
  const interfaceType = props.match.path.includes('mainSpareInterface');
  const dataSourceType = interfaceType ? 2 : 3;
  const id = props.match.params.id;

  useEffect(() => {
    id && getInnerInterfaceDetail();
  }, []);

  const handleTabChange = (key) => {
    setActiveKey(key);
  };

  // 监听数据源改变
  const onThirdInterfaceChange = (thirdList, changeObj) => {
    setValue((prevState) => ({
      ...prevState,
      thirdList,
      changeObj,
    }));
  };

  // 获取计费配置json
  const getPriceJson = (priceJson) => {
    const tempValue = { ...value };
    tempValue['priceJson'] = priceJson;
    setValue(tempValue);
  };

  const getInnerInterfaceDetail = async () => {
    const { code, msg, data } = await services.interfaceManage.detail(id);
    if (code) return message.error(msg);
    setValue((prevState) => ({
      ...prevState,
      ...data,
    }));
  };

  const handleSubmit = () => {
    form.validateFields(async (errors, values) => {
      if (!errors) {
        const { priceJson } = value;
        let params = {};
        try {
          params = {
            dataSourceType,
            ...values,
            priceJson,
            ...defineInterfaceRef.current.getDiData(),
          };
        } catch (error) {
          return message.warning(error);
        }
        const { thirdInterfaceList, feeRules } = params;
        thirdInterfaceList.forEach((item) => {
          item['interfaceId'] = item.id;
        });
        // 计费规则 如果外部数据源没有计费配置 则thirdFeeRuleList为[]
        feeRules.forEach(({ thirdFeeRuleList }, index) => {
          if (thirdFeeRuleList.every((item) => !item.code && !item.name)) {
            feeRules[index].thirdFeeRuleList = [];
          }
        });
        const isFull = feeRules.some((item) => !item.name || !item.code);
        if (isFull) params.feeRules = [];
        const { code, msg } = await services.interfaceManage[id ? 'update' : 'add']({ id, ...params });
        if (!code) {
          message.success('操作成功');
          props.history.push('/dataGateway/mainSpareInterface');
        } else {
          message.error(msg);
        }
      }
    });
  };

  const renderInterfaceNodes = () => (
    <div className='add_interface'>
      <DefineInterface
        {...props}
        handleDataSourceChange={handleDataSourceChange}
        value={value}
        ref={defineInterfaceRef}
        getPriceJson={getPriceJson}
        interfaceType={interfaceType}
        onThirdInterfaceChange={onThirdInterfaceChange}
        id={id}
      />
    </div>
  );

  const renderRuturnNodes = () => (
    <div className='add_interface'>
      <DefineReturn {...props} ref={defineReturnRef} value={value} interfaceType={interfaceType} />
    </div>
  );

  const handleDataSourceChange = (value) => {
    value && getParamsByThird(value);
  };

  // 根据选择的数据源渲染 入参 出参 映射
  const getParamsByThird = async (interfaceId) => {
    const thirdInterfaceList = [{ interfaceId }];
    const {
      data: { params, feeRules, successExample, returningType },
    } = await services.dataSource.detail(interfaceId);
    const enterParams = params
      .filter((item) => !item.val)
      .map((item) => {
        const { name, position, type, nonEmpty, id: paramId } = item;
        const tempObj = {
          thirdParamList: [
            {
              ...item,
              interfaceId,
              paramId,
            },
          ],
          // 入参设置默认值
          name,
          position,
          type,
          nonEmpty,
        };
        return tempObj;
      });
    const constantParam = params.filter((item) => item.val);
    const thirdFeeRuleList = feeRules.map((item) => {
      return {
        ...item,
        interfaceId,
        feeRuleId: item.id,
      };
    });
    const newFeeRules = {
      name: '',
      code: '',
      feeRuleType: 1,
      thirdFeeRuleList,
    };
    const tempObj = {
      tpSuccessExample: successExample,
      tpReturningType: returningType,
      enterParams,
      constantParam,
      feeRules: [newFeeRules],
    };
    setValue({
      ...value,
      ...tempObj,
      thirdInterfaceList,
    });
  };

  const handleNext = () => {
    form.validateFields(['name', 'flag', 'isRateLimit', 'rateMax', 'groupId', 'feeType'], (error) => {
      if (!error) return setActiveKey('1');
    });
  };

  return (
    <div className='add'>
      <Form autoComplete='off'>
        <Tabs style={{ width: '100%' }} activeKey={activeKey} onChange={handleTabChange}>
          <Tabs.TabPane tab={'定义接口'} key='0' forceRender={true}>
            {renderInterfaceNodes()}
          </Tabs.TabPane>
          <Tabs.TabPane tab={'定义返回'} key='1' forceRender={true}>
            {renderRuturnNodes()}
          </Tabs.TabPane>
        </Tabs>
        <Row type='flex' justify='start' className='operate_button'>
          <Col>
            {activeKey === '1' ? (
              <Button type='primary' onClick={handleSubmit}>
                保存
              </Button>
            ) : (
              <Button type='primary' onClick={handleNext}>
                下一步
              </Button>
            )}
          </Col>
        </Row>
      </Form>
    </div>
  );
};
export default Form.create()(InterfaceManageAdd);
